package com.example.mypplication.component

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.motion.widget.MotionLayout
import com.example.mypplication.R

class Component3Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_component3)

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)

        // 设置适配器
        val items = List(50) { index -> "Item ${index + 1}" }
        recyclerView.adapter = SimpleAdapter(items)

        // 添加滚动监听器以处理边界情况
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val motionLayout = findViewById<MotionLayout>(R.id.motionLayout)

                // 如果列表在顶部且向下滑动，确保状态是展开的
                if (!recyclerView.canScrollVertically(-1) && dy < 0) {
                    motionLayout.transitionToState(R.id.expanded)
                }
                // 如果列表不在顶部且向上滑动，允许过渡到折叠状态
                else if (recyclerView.canScrollVertically(-1) && dy > 0) {
                    // 由 MotionLayout 自动处理
                }
            }
        })
    }

    // 简单的适配器
    private inner class SimpleAdapter(private val items: List<String>) :
        RecyclerView.Adapter<SimpleAdapter.ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(android.R.layout.simple_list_item_1, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.textView.text = items[position]
        }

        override fun getItemCount(): Int = items.size

        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val textView: TextView = itemView.findViewById(android.R.id.text1)
        }
    }
}